/**
 * 开始界面管理器
 */
cc.Class({
    extends: cc.Component,

    properties: {
        /**
         * 分享文字
         */
        shareText: {
            default: "",
            tooltip: "分享时显示的文字"
        },
        /**
         * 显示排行榜的图片
         */
        rankDisplay: cc.Sprite,
        /**
         * 排行榜面板
         */
        rankPanel: cc.Node,
    },

    onLoad () {
        //加载游戏场景
        cc.director.preloadScene("Game", function () {
            cc.log("Game scene preloaded");
        });
        this.openWxShare();
        this._isOpeningRank = false;
    },

    start () {
        this.onCloseRankBtnClick();
        this.rankTex = new cc.Texture2D();
    },

    update (dt) {
        this.updaetSubDomainCanvas();
    },

    /**
     * 点击开始按钮
     */
    onStartBtnClick () {
        if (this._isOpeningRank) return;
        cc.director.loadScene('Game');
        if (CC_WECHATGAME) {
            wx.postMessage({
                message: 'ChangeScene'
            });
        }
    },

    /**
     * 点击好友排行榜按钮
     */
    onRankBtnClick () {
        if (this._isOpeningRank) return;
        this._isOpeningRank = true;
        this.rankPanel.active = true;
        if (!CC_WECHATGAME) return;
        wx.postMessage({
            message: 'ShowRank'
        });
    },

    /**
     * 关闭好友排行榜按钮
     */
    onCloseRankBtnClick () {
        this._isOpeningRank = false;
        this.rankPanel.active = false;
        if (!CC_WECHATGAME) return;
        wx.postMessage({
            message: 'HideRank'
        });
    },

    /**
     * 更新子域的排行榜显示
     */
    updaetSubDomainCanvas () {
        if (!this.rankTex || !CC_WECHATGAME || !this._isOpeningRank) return;
        var openDataContext = wx.getOpenDataContext();
        var sharedCanvas = openDataContext.canvas;
        this.rankTex.initWithElement(sharedCanvas);
        this.rankTex.handleLoadedTexture();
        this.rankDisplay.node.setContentSize(cc.director.getVisibleSize());
        this.rankDisplay.spriteFrame = new cc.SpriteFrame(this.rankTex);
    },

    /**
     * 打开微信小程序右上角的分享功能
     */
    openWxShare () { 
        if (!CC_WECHATGAME) return;
        //开启微信的转发.
        wx.showShareMenu();
        //监听右上角的分享调用 
        wx.onShareAppMessage(function(res){
            return {
                title: "我们的旋转",
                imageUrl: cc.url.raw("resources/image/share.png")
            }
        });
    },

    /**
     * 点击分享按钮
     */
    onShareBtnClick () {
        if (this._isOpeningRank) return;
        if (!CC_WECHATGAME) return;
        wx.shareAppMessage({
            title: this.shareText,
            imageUrl: cc.url.raw("resources/image/share.png")
        });
    },
});
